package com.wish.nettywithpack;

import com.wish.common.MyUtils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

/**
 * 用于对网络事件进行读写操作
 *
 * @author tantexian
 * @since 2016/7/12
 * @params
 */
class LineBasedAndStringServerHandle extends ChannelHandlerAdapter {
    private int count = 0;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        String body = (String)msg;
        System.out.println("[" + (++count) + "] " + "I'm Delimiter server, I has receive " + body);

        // 通过获取到client发过来的信息body，获取对应的answer
        String answer = MyUtils.getAnswer(body) + "\n";
        ByteBuf answerBuf = Unpooled.copiedBuffer(answer.getBytes());
        // 异步发送消息给客户端
        // 为了性能考虑netty中write并不会立即将消息发送给对方，只是放置到发送缓冲区数组中，
        // 只有调用ctx.flush()才将缓冲区中消息写入到SocketChannel中发送给对方
        ctx.writeAndFlush(answerBuf);
    }


    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        // 将消息队列中的消息写入到SocketChannel中发送给对方
        ctx.flush();
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
